package com.yinshan.avchatdemo.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;
import com.yinshan.avchatdemo.R;
import com.yinshan.avchatkit.AVChatKit;
import com.yinshan.avchatkit.activity.AVChatActivity;

import java.util.Arrays;
import java.util.List;

public class AVChatCallActivity extends AppCompatActivity {


    private Button StartRTSButton;  //发起白板会话的按钮
    private EditText toAccountText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_startcall);
        //初始化界面
        initView();

        StartRTSButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String toAccount = toAccountText.getText().toString();
                if (!toAccount.isEmpty()) {
                    NimUserInfo user = NIMClient.getService(UserService.class).getUserInfo(toAccount);
                    if (user == null) {
                        String[] array = {toAccount};
                        List<String> accounts = Arrays.asList(array);
                        NIMClient.getService(UserService.class).fetchUserInfo(accounts)
                                .setCallback(new RequestCallback<List<NimUserInfo>>() {
                                    @Override
                                    public void onSuccess(List<NimUserInfo> nimUserInfos) {
                                        if (!nimUserInfos.isEmpty()) {
                                            NimUserInfo nimUserInfo = nimUserInfos.get(0);
                                            Log.d("RTSActivity", "onSuccess: 获取到" + nimUserInfo.getAccount() + "的云端资料");
                                            AVChatKit.outgoingCall(AVChatCallActivity.this, nimUserInfo.getAccount(), "DB28437", "{\"code\":\"CA_1558521510399002\"}", AVChatActivity.FROM_INTERNAL);
                                        } else {
                                            Toast.makeText(AVChatCallActivity.this, "请检查对方账号是否存在！", Toast.LENGTH_SHORT).show();
                                        }
                                    }

                                    @Override
                                    public void onFailed(int i) {
                                        Log.e("RTSActivity", "onFailed: 获取云端好友资料失败,错误码：" + i);
                                    }

                                    @Override
                                    public void onException(Throwable throwable) {

                                    }
                                });
                    } else {
                        AVChatKit.outgoingCall(AVChatCallActivity.this, user.getAccount(), "DB28437", "{\"code\":\"CA_1558521510399002\"}", AVChatActivity.FROM_INTERNAL);
                    }
                }
            }
        });
    }

    private LocalBroadcastManager localBroadcastManager;
    private RecordReceiver recordReceiver;

    /**
     * 初始化界面
     */
    private void initView() {
        StartRTSButton = findViewById(R.id.startrts);
        toAccountText = findViewById(R.id.toaccountid);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AVChatActivity.ACTION_SINGAL_STATUS);
        recordReceiver = new RecordReceiver();
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localBroadcastManager.registerReceiver(recordReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(recordReceiver);
    }

    /**
     * 点击空白位置 隐藏软键盘
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    private class RecordReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(final Context context, Intent intent) {
            if (null == intent) return;
            Log.d("", "收到广播:" + intent.getAction());
            if (AVChatActivity.ACTION_SINGAL_STATUS.equals(intent.getAction())) {
                switch (intent.getStringExtra(AVChatActivity.KEY_FACE_STATUS)) {
                    //视频成功呼出
                    case AVChatActivity.FACE_STATUS_SERVER_START:
                        String channelID = intent.getStringExtra("channelID");
                        Toast.makeText(context, "呼出成功：" + channelID, Toast.LENGTH_SHORT).show();
                        break;
                    case AVChatActivity.STEP_SIGNAL_RESULT_SUCCESS:
                        Toast.makeText(context, "视频面签成功", Toast.LENGTH_SHORT).show();
                        break;
                    case AVChatActivity.STEP_SIGNAL_RESULT_FAIL:
                        Toast.makeText(context, "视频面签失败，请重试", Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }
    }
}
